<template>
    <div class="gpt-all-bg">
        <div class="gpt-content-bg">
            <el-scrollbar class="scrollbar" ref="scrollbar" @scroll="scrollbarChange">
                <el-button :class="{
                    goUnderChange: scrollbarHeight < 500 && chatHistory.length > 10,
                }" class="goToUnder" :icon="ArrowDownBold" @click="Refresh" circle />

                <div class="gpt-content" v-for="(item, key) in chatHistory" :key="key">
                    <Chat_Gpt_UserChat v-if="item.isUser" class="gpt-user" :mess="item.mess" />
                    <Chat_Gpt_GptChat @goUnder="Refresh" @printOK="closeANI" v-else class="gpt-chat" :mess="item.mess"
                        :now="item.now" />
                </div>

            </el-scrollbar>
        </div>
        <div class="gpt-bottom">
            <el-input @keyup.shift.enter.exact="sendMess" v-model="userinput" maxlength="1000" type="textarea"
                show-word-limit placeholder="请输入内容,Enter换行,Shift+Enter发送"></el-input>
            <el-button type="primary" round :disabled="userinputflag" @click="sendMess">发送</el-button>
        </div>
    </div>
</template>

<script setup lang='js' name=''>
import { ref, watch, nextTick,defineExpose } from 'vue'
import Chat_Gpt_GptChat from './Chat_Gpt_GptChat.vue';
import Chat_Gpt_UserChat from './Chat_Gpt_UserChat.vue';
import { CheckInput } from '@/hooks/userCheckInput';
import getDialogueAPI from '@/API/main/ChatGPT/Dialogue';
import getSelectSessionRecordAPI from '@/API/main/ChatGPT/selectSessionRecord';
import showMessage from '@/utils/showMessage';
import { ArrowDownBold } from '@element-plus/icons-vue'

const userinputflag = ref(true)
const userinput = ref("")
const chatHistory = ref([])

// 监听输入
watch(userinput, () => {
    if (userinput.value) {
        userinputflag.value = false
    } else {
        userinputflag.value = true
    }
})

// 发送内容
async function sendMess() {
    if (CheckInput(userinput.value, "请输入内容")) {
        userinput.value = userinput.value.trim()
        chatHistory.value.push({ isUser: true, mess: userinput.value })
        Refresh()
        const mess = userinput.value
        userinput.value = ""
        chatHistory.value.push({ isUser: false, mess: "正在加载中...", now: true })
        const res = await getDialogueAPI(mess)
        if (res) {
            if (res.status == 200) {
                chatHistory.value.pop()
                await nextTick()
                chatHistory.value.push({ isUser: false, mess: res.data.content, now: true })
            } else {
                showMessage("对话失败")
            }
        } else {
            console.log(res)
        }

    }
}

function closeANI() {
    delete chatHistory.value[chatHistory.value.length - 1]["now"]
}

// 滚动条
const scrollbar = ref("")
const scrollbarHeight = ref(0)
const scrollbarNowHeight = ref(0)
const startPage = ref(0)
const endPage = ref(20)

// 对话记录
async function loadChatHistory(flag) {
    if (!flag) {
        chatHistory.value = []
    }
    const res = await getSelectSessionRecordAPI(startPage.value, endPage.value)
    if (res.status == 200) {
        // console.log(res)
        res.data.forEach(element => {
            chatHistory.value.unshift({ isUser: element.identity == 1, mess: element.content })
        });
        await Refresh()
        if (flag) {
            await scrollbarGoTo()
        }
        if (!flag) {
            setTimeout(() => {
                Refresh()
            }, 10);
        }
    } else {
        showMessage("加载对话记录失败:" + res.msg)
    }
}
loadChatHistory()
defineExpose({loadChatHistory})
// 获取滚动条位置
function scrollbarChange(e) {
    scrollbarHeight.value = e.scrollTop
    if (scrollbarNowHeight.value == 0) {
        scrollbarNowHeight.value = scrollbarHeight.value
    }
}

// 回到底部
async function Refresh() {
    await nextTick()
    scrollbar.value.setScrollTop(999999999999999)
    scrollbar.value.handleScroll()
}

watch(scrollbarHeight, () => {
    if (scrollbarHeight.value == 0 && chatHistory.value.length >= startPage.value + 20) {
        startPage.value = startPage.value + 20
        loadChatHistory(true)
    }
})

async function scrollbarGoTo() {
    await nextTick()
    let nowHeight = scrollbarHeight.value - scrollbarNowHeight.value
    scrollbar.value.handleScroll()
    scrollbarNowHeight.value = scrollbarHeight.value
    scrollbar.value.setScrollTop(nowHeight)
}
</script>

<style scoped>
.gpt-all-bg {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
}

.gpt-content-bg {
    height: calc(100% - 70px);
}

.gpt-content {
    display: flex;
    flex-direction: column;
}

.gpt-bottom {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 70px;
    display: flex;
    gap: 10px;
    justify-content: center;
    align-items: center;
}

:deep(.el-textarea__inner) {
    resize: none;
    overflow: hidden;
    font-size: 14px;
    height: 100%;
}

.el-textarea {
    resize: none;
    width: 70%;
    max-height: 50px;
    /* overflow: hidden; */
}

.el-button {
    height: 50px;
    width: 20%;
}

.gpt-chat {
    margin: 5px 0px;
}

.gpt-user {
    margin: 5px 0px;
    align-self: flex-end;
}

.scrollbar {
    position: relative;
}

.goToUnder {
    position: absolute;
    width: 30px;
    height: 30px;
    top: 0px;
    right: 10px;
    transition: all 0.5s;
    opacity: 0;
    pointer-events: none;

}

.goUnderChange {
    opacity: 1 !important;
    pointer-events: visiblePainted !important;
}
</style>